import shop from '../../api/shop'

const state = {
    added: [],
    setCheckoutStatus: null
}

const getters = {
    cartProducts: (state, getters, rootState) => {
        return state.added.map(function (cartProduct) {
            const product = rootState.products.all.find(function (product) {
                return product.id === cartProduct.id
            })
            return {
                id:product.id,
                title: product.title,
                price: product.price,
                quantity: cartProduct.quantity
            }
        })
    },

    cartTotalPrice: (state, getters) => {
        return getters.cartProducts.reduce(function(total, product){
            return total + product.price * product.quantity
        }, 0)
    },

    checkoutStatus: (state) => {
        return state.setCheckoutStatus
    }
}

const actions = {
    //结账
    checkout: (context, products) => {
        const savedCartItems = [].concat(context.state.added)
        context.commit('setCheckoutStatus', null)

        context.commit('setCartItems', {items:[]})
        shop.buyProducts(
            products,
            function(){
                context.commit('setCheckoutStatus','成功')
            },
            function(){
                context.commit('setCheckoutStatus','失败')
            })
    },

    //向购物车添加商品
    addProductToCart: (context, product) => {
        context.commit('setCheckoutStatus', null)
        if (product.inventory > 0) {
            const cartItem = context.state.added.find(function (cartProduct) {
                return cartProduct.id === product.id
            })
            if (!cartItem) {
                context.commit('pushProductToCart', { id: product.id })
            } else {
                context.commit('incrementItemQuantity', cartItem)
            }
            context.commit('decrementProductInventory', { id: product.id })
        }
    }
}

const mutations = {
    //设置提示结账成功与否
    setCheckoutStatus: (state, payload) => {
        state.setCheckoutStatus = payload
    },

    pushProductToCart: (state, payload) => {
        state.added.push({//?
            id: payload.id,
            quantity: 1
        })
    },

    incrementItemQuantity: (state, payload) => {
        const cartItem = state.added.find(function (cartProduct) {
            return cartProduct.id === payload.id
        })
        cartItem.quantity++
    },

    //用于结账后清空购物车，payload为{items:[]}
    setCartItems: (state, payload) => {
        state.added = payload.items
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}